<?php

class Administration_Model_User extends Zend_Db_Table_Abstract {

    protected $_name = 'user';

    function listUsers() {
        $select = $this->select()->setIntegrityCheck(FALSE)->from("user", array("*", "user.id as uId"))->join("role", "user.roleId=role.id");
        return $this->fetchAll($select)->toArray();
    }

    function addUser($userInfo) {
        $row = $this->createRow();
        $row->firstName = $userInfo['firstName'];
        $row->lastName = $userInfo['lastName'];
        $row->email = $userInfo['email'];
        $row->password = md5($userInfo['password']);
        $row->gender = $userInfo['gender'];
        //generate random name for the image to prevent overriding (Not implemented !)
        if ($userInfo['image']) {
            //get image extention
            $imageExt = substr(strrchr($userInfo['image'], '.'), 1);
            $randomName = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
            $userInfo['image'];
        }
        $row->image = $userInfo['image'];
        $row->isEnabled = $userInfo['isEnabled'];
        $row->roleId = $userInfo['roleId'];
        $row->jobTitle = $userInfo['jobTitle'];
        $row->description = $userInfo['description'];
        $row->facebook = $userInfo['facebook'];
        $row->twitter = $userInfo['twitter'];
        $row->linkedin = $userInfo['linkedin'];
        $row->google = $userInfo['google'];
        $row->intake = $userInfo['intake'];
        $row->track = $userInfo['track'];
        return $row->save();
    }

    function editUser($userId, $userInfo) {

        //add updated on field
        $userInfo['updatedOn'] = date('Y-m-d H:i:s');
        //unset retype password
        unset($userInfo['passwordRetype']);
        //if password empty remove password
        if (empty($userInfo['password'])) {
            unset($userInfo['password']);
        } else {
            $userInfo['password'] = md5($userInfo['password']);
        }
        //if image empty remove image
        if (empty($userInfo['image']) && empty($userInfo['removeImage'])) {
            unset($userInfo['image']);
            unset($userInfo['removeImage']);
        } else {
            unset($userInfo['removeImage']);
        }
        
        //unset email
        if ($userInfo['email']) {
            unset($userInfo['email']);
        }
        return $this->update($userInfo, "id = $userId");
    }

    function getUserById($userId) {
        return $this->find($userId)->toArray();
    }

    function deleteUser($userId) {
        return $this->delete("id = $userId");
    }

}
